<template>
	<view>
		<text></text>
		<text>{{timeStr}}</text>
		<view v-if="testButton">
			<button type="default" @click="start()">开始</button>
			<button type="default" @click="clear()">暂停</button>
			<button type="default" @click="reset()">重置</button>
			<button type="default" @click="getTimeCount()">获取当前秒数</button>
		</view>
	</view>
</template>

<script>
	export default {
		name: "mryzr-timer",
		emits: ['callbackTimeCode', 'update:modelValue'],
		model: {
			props: 'modelValue',
			event: 'update:modelValue'
		},
		props: {
			value: [Number, String],
			modelValue: [Number, String],
			testButton: {
				type: Boolean,
				default: false
			},
			auto: {
				type: Boolean,
				default: true
			},
			format: {
				type: String,
				default: 'day天HH:mm:ss'
			},
			
			prefix: {
				type: String,
				default: ''
			},
		},
		watch: {
			value(newVal) {
				this.timeCount = newVal || 0
			},
			modelValue(newVal) {
				this.timeCount = newVal || 0
			},
			timeCount: function(newVal) {
				this.countToTime(newVal)
				// TODO 兼容 vue2
				this.$emit('input', newVal);
				// TODO　兼容　vue3
				this.$emit('update:modelValue', newVal)
			}
		},
		created() {
			this.init();
			if (this.auto) {
				this.start()
			}
		},
		data() {
			return {
				timeCount: 0,
				day: '0',
				hh: '00',
				mm: '00',
				ss: '00',
				interval: null
			};
		},
		computed: {
			timeStr() {
				let formatStr = this.format + "";
				formatStr = formatStr.replace(/day/g, this.day);
				formatStr = formatStr.replace(/HH/g, this.hh);
				formatStr = formatStr.replace(/mm/g, this.mm);
				formatStr = formatStr.replace(/ss/g, this.ss);
				return formatStr;
			}
		},
		methods: {
			/**
			 * 初始化变量值
			 */
			init() {
				if (this.value || this.value === 0) {
					this.timeCount = this.value
				} else if (this.modelValue || this.modelValue === 0) {
					this.timeCount = this.modelValue
				} else {
					this.timeCount = 0
				}
			},
			start() {
				if (!this.interval) {
					this.interval = setInterval(() => {
						this.timeCount++
					}, 1000)
				}
			},
			clear() {
				clearInterval(this.interval)
				this.interval = null
			},
			reset() {
				clearInterval(this.interval)
				this.interval = null
				this.timeCount = 0
				this.day = '0'
				this.hh = '00'
				this.mm = '00'
				this.ss = '00'
			},
			countToTime(countDown) {
				// 转换为式分秒
				let d = parseInt(countDown / 60 / 60 / 24);
				let h = parseInt(countDown / 60 / 60 % 24);
				h = h < 10 ? '0' + h : h;
				let m = parseInt(countDown / 60 % 60);
				m = m < 10 ? '0' + m : m;
				let s = parseInt(countDown % 60);
				s = s < 10 ? '0' + s : s;
				this.day = d;
				this.hh = h;
				this.mm = m;
				this.ss = s;
				return countDown;
			},
			getTimeCount() {
				return this.timeCount;
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
